<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/8/19
 * Time: 15:54
 */

namespace app\api\controller;


use think\Db;

class Order extends Base
{
    private $user_id;
    private $create_time;
    private $page;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
    }
    
    /**
     * 出售订单（合并了）
     * @return \think\response\Json
     * order_status     订单状态   0 全部   1 待审核   2 已同意   3 已放款   4 拒绝/取消
     * page             页码
     */
//    public function saleOrder(){
//        $order_status = input('order_status'); // 0 全部   1 待审核   2 已同意  3 已放款  4 拒绝/取消
//        $where['order_type'] = 1;
//        $where['order_user_id'] = $this->user_id;
//        if($order_status == 1){
//            $where['order_status'] = 1;
//        }elseif($order_status == 2){
//            $where['order_status'] = 2;
//        }elseif($order_status == 3){
//            $where['order_status'] = 3;
//        }elseif($order_status == 4){
//            $where['order_status'] = ['IN', [4, 5]];
//        }
//        $order = Db::table('up_order')
//            ->join('up_cate', 'cate_id = order_cate_id', 'LEFT')
//            ->join('up_brand', 'brand_id = order_brand_id', 'LEFT')
//            ->join('up_models', 'models_id = order_models_id', 'LEFT')
//            ->where($where)
//            ->field('order_id, order_status, order_number, order_old_price, cate_name, brand_name,
//            models_name, order_ri_ids')
//            ->order('order_time desc')
//            ->page($this->page, 10)
//            ->select();
//        if($order){
//            foreach($order as $k => $v){
//                $info = Db::table('up_recycle_info')
//                    ->where('ri_id', 'IN', $v['order_ri_ids'])
//                    ->column('ri_name');
//                $ri_name = implode('/', $info);
//                $order[$k]['ri_name'] = $ri_name;
//            }
//            return json(['status' => 200, 'msg' => $order]);
//        }else{
//            return json(['status' => 200, 'msg' => []]);
//        }
//    }
    
    /**
     * 出售订单详情
     * @return \think\response\Json
     * order_id       订单ID
     */
    public function saleOrderDetail(){
        $order_id = input('order_id');
        // 订单
        $order = Db::table('up_order')
            ->join('up_cate', 'cate_id = order_cate_id', 'LEFT')
            ->join('up_brand', 'brand_id = order_brand_id', 'LEFT')
            ->join('up_models', 'models_id = order_models_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_id, order_tag, order_number, order_status, order_old_price, order_time, order_check_time, 
            order_payfor_time, order_shop_id, order_ri_ids, order_remark, order_payfor_time, cate_name, brand_name, models_name')
            ->find();
        // 店铺
        $shop = Db::table('up_shop')
            ->join('up_area a1', 'a1.district_id = shop_sheng', 'LEFT')
            ->join('up_area a2', 'a2.district_id = shop_shi', 'LEFT')
            ->join('up_area a3', 'a3.district_id = shop_qu', 'LEFT')
            ->where('shop_id', $order['order_shop_id'])
            ->field('shop_name, shop_image, shop_addr, a1.district sheng, a2.district shi, a3.district qu, 
            shop_user_phone')
            ->find();
        // 回收故障小项
        $ri_names = Db::table('up_recycle_info')
            ->where('ri_id', 'IN', $order['order_ri_ids'])
            ->column('ri_name');
        $order['order_ri_name'] = implode('/', $ri_names);
        $order['order_clock_time'] = date("Y-m-d H:i:s", (strtotime($order['order_time']) + (3600*24*5)));
        return json(['status' => 200, 'msg' => $order, 'shop' => $shop]);
    }
    
    /**
     * 取消订单
     * @return \think\response\Json
     * order_id       订单ID
     */
    public function cancelOrder(){
        $order_id = input('order_id');
        $res = Db::table('up_order')
            ->where('order_id', $order_id)
            ->setField('order_status', 5);
        if($res){
            return json(['status' => 200, 'msg' => '取消成功']);
        }else{
            return json(['status' => 0, 'msg' => '取消失败']);
        }
    }
    
    /**
     * 出售/寄存订单列表
     * @return \think\response\Json
     * order_status    0 全部   1 待审核   2 已同意   3 已放款   4 拒绝/取消
     * page            页面
     */
    public function myOrder(){
        $order_type = input('type');
        $order_status = input('order_status'); // 0 全部   1 待审核   2 已同意  3 已放款  4 拒绝/取消
        $where['order_type'] = $order_type;
        $where['order_user_id'] = $this->user_id;
        if($order_status == 1){
            $where['order_status'] = 1;
        }elseif($order_status == 2){
            $where['order_status'] = 2;
        }elseif($order_status == 3){
            $where['order_status'] = 3;
        }elseif($order_status == 4){
            $where['order_status'] = ['IN', [4, 5]];
        }
        $order = Db::table('up_order')
            ->join('up_cate', 'cate_id = order_cate_id', 'LEFT')
            ->join('up_brand', 'brand_id = order_brand_id', 'LEFT')
            ->join('up_models', 'models_id = order_models_id', 'LEFT')
            ->where($where)
            ->field('order_id, order_tag, order_status, order_number, order_old_price, cate_name, brand_name, 
            models_name, order_ri_ids, order_jc_days, order_jc_price')
            ->order('order_time desc')
            ->page($this->page, 10)
            ->select();
        if($order){
            foreach($order as $k => $v){
                $info = Db::table('up_recycle_info')
                    ->where('ri_id', 'IN', $v['order_ri_ids'])
                    ->column('ri_name');
                $ri_name = implode('/', $info);
                $order[$k]['ri_name'] = $ri_name;
            }
            return json(['status' => 200, 'msg' => $order]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 寄存订单详情
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function consignOrderDetail(){
        $order_id = input('order_id');
        // 订单
        $order = Db::table('up_order')
            ->join('up_cate', 'cate_id = order_cate_id', 'LEFT')
            ->join('up_brand', 'brand_id = order_brand_id', 'LEFT')
            ->join('up_models', 'models_id = order_models_id', 'LEFT')
            ->where('order_id', $order_id)
            ->field('order_id, order_tag, order_number, order_status, order_old_price, order_time, order_check_time, 
            order_is_pay,order_payfor_time, order_shop_id, order_ri_ids, order_remark, order_payfor_time, order_jc_price, 
            order_jc_days, order_jc_sy_days,cate_name, brand_name, models_name, order_is_consign,order_jc_datetime,order_jc_total_days')
            ->find();
        // 如果有续存订单，则要找出最新一条寄存订单状态
        if($order['order_is_consign'] != 1){
            $xucun = Db::table('up_order_info')
                ->where('oi_order_id', $order['order_id'])
                ->where('oi_type', 2)
                ->order('oi_id desc')
                ->field('oi_status,oi_zhejiu_price')
                ->find();
            $order['oi_status'] = $xucun['oi_status'];
            $order['oi_zhejiu_price'] = $xucun['oi_zhejiu_price'];
        }
        // 店铺
        $shop = Db::table('up_shop')
            ->join('up_area a1', 'a1.district_id = shop_sheng', 'LEFT')
            ->join('up_area a2', 'a2.district_id = shop_shi', 'LEFT')
            ->join('up_area a3', 'a3.district_id = shop_qu', 'LEFT')
            ->where('shop_id', $order['order_shop_id'])
            ->field('shop_name, shop_image, shop_addr, a1.district sheng, a2.district shi, a3.district qu, 
            shop_user_phone')
            ->find();
        // 回收故障小项
        $ri_names = Db::table('up_recycle_info')
            ->where('ri_id', 'IN', $order['order_ri_ids'])
            ->column('ri_name');
        $order['order_ri_name'] = implode('/', $ri_names);
        $order['order_clock_time'] = date("Y-m-d H:i:s", (strtotime($order['order_time']) + (3600*24*5)));
        return json(['status' => 200, 'msg' => $order, 'shop' => $shop]);
    }
    
    /**
     * 续存
     * @return \think\response\Json
     * days       续存天数
     * order_id   订单ID
     */
    public function xucunOrder(){
        $days = (int)input('days');
        $order_id = input('order_id');
        if($days < 3 || $days > 30){
            return json(['status' => 0, 'msg' => '续存天数不能低于3天或大于30天']);
        }
        // 到期时间
        $order = Db::table('up_order')
            ->where('order_id', $order_id)
            ->field('order_jc_datetime, order_jc_date, order_jc_total_days, order_jc_sy_days')
            ->find();
        $dq_time = date('Y-m-d H:i:s', strtotime("+{$days}days", strtotime($order['order_jc_datetime'])));
        $dq_date = date('Y-m-d', strtotime("+{$days}days", strtotime($order['order_jc_date'])));
        
        
        // 保管费
        $serve_price = Db::table('up_serve_price')
            ->where('sp_days', $days)
            ->value('sp_price');
        
        Db::startTrans();
        try{
            // 更新总订单表
            $update = [
                'order_is_consign' => 3,
//                'order_jc_total_days' => $order['order_jc_total_days'] + $days,
//                'order_jc_days' => $days,
//                'order_jc_sy_days' => $order['order_jc_sy_days'] + $days,
//                'order_jc_price' => $serve_price,
//                'order_jc_datetime' => $dq_time,
//                'order_jc_date' => $dq_date,
                'order_is_pay' => 1
            ];
            Db::table('up_order')->where('order_id', $order_id)->update($update);
            $oi_order_number = 'ci_' . date('YmdHis') . rand(1000, 9999);
            
            // 插入续存明细
            $insert = [
                'oi_order_id' => $order_id,
                'oi_days' => $days,
                'oi_price' => $serve_price,
                'oi_date' => $dq_date,
                'oi_datetime' => $dq_time,
                'oi_time' => $this->create_time,
                'oi_type' => 2,
                'oi_order_number' => $oi_order_number
            ];
            Db::table('up_order_info')->insert($insert);
            
            Db::commit();
            return json(['status' => 200, 'msg' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
        
    }
    
    /**
     * 还款
     * @return \think\response\Json
     * order_id
     */
    public function returnOrder(){
        $order_id = input('order_id');
        
        $oi = Db::table('up_order_info')
            ->where('oi_order_id', $order_id)
            ->field('oi_days, oi_price, oi_date, oi_datetime, oi_zhejiu_price')
            ->order('oi_time desc')
            ->find();
        
        Db::startTrans();
        try{
            // 更新总订单表
            $update = [
                'order_is_consign' => 2,
//                'order_jc_total_days' => $order['order_jc_total_days'] + $days,
//                'order_jc_days' => $days,
//                'order_jc_sy_days' => $order['order_jc_sy_days'] + $days,
//                'order_jc_price' => $serve_price,
//                'order_jc_datetime' => $dq_time,
//                'order_jc_date' => $dq_date,
                'order_is_pay' => 1
            ];
            Db::table('up_order')->where('order_id', $order_id)->update($update);
            $oi_order_number = 'ci_' . date('YmdHis') . rand(1000, 9999);
    
            // 插入续存明细
            $insert = [
                'oi_order_id' => $order_id,
                'oi_days' => $oi['oi_days'],
                'oi_price' => $oi['oi_price'],
                'oi_date' => $oi['oi_date'],
                'oi_datetime' => $oi['oi_datetime'],
                'oi_time' => $this->create_time,
                'oi_type' => 2,
                'oi_status' => 2,
                'oi_order_number' => $oi_order_number,
                'oi_cate' => 2
            ];
            Db::table('up_order_info')->insert($insert);
    
            Db::commit();
            return json(['status' => 200, 'msg' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 续存缴费明细展示（续费和还款都用这个吧）
     * @return \think\response\Json
     * order_id      订单ID
     * type  1续租  2还款
     */
    public function showPay(){
        $order_id = input('order_id');
        $type = input('type');
        if($type != 1 && $type != 2){
            return json(['status' => 0, 'msg' => '参数有误！']);
        }
        //直接查订单就可以：
        //如果是续租缴费（后台审核同意的时候就把折旧费更新到主表了）
            // 续租的费用 order_jc_price+order_jc_zhejiu_price：
        //如果是还款
            // 还款的费用 order_jc_now_price+order_jc_price：
        $order = Db::table('up_order')
            ->where('order_id', $order_id)
            ->find();
        if($type == 1){
            $order['total_price'] = $order['order_jc_price'] + $order['order_jc_zhejiu_price'];
        }else{
            $order['total_price'] = $order['order_jc_now_price'] + $order['order_jc_price'];
        }
//        $oi = Db::table('up_order_info')
//            ->where('oi_order_id', $order_id)
//            ->where('oi_type', 2)
//            ->field('oi_days, oi_price, oi_zhejiu_price')
//            ->order('oi_time desc')
//            ->page(2,1)
//            ->find();
//        $order['days'] = $oi['oi_days'];
//        $order['zhejiu_price'] = $oi['oi_zhejiu_price'];
//        $order['serve'] = $oi['oi_price'];
//        $order['total_price'] = $oi['oi_price'] + $oi['oi_zhejiu_price'];
        return json(['status' => 200, 'msg' => $order]);
    }
    public function QRcodePay()
    {
        $order_id = input('order_id');
        $type = input('type');
        $money = input('money');
        $miniCode = input('miniCode');
        $openid = $this->getOpenId($miniCode);
        if ($openid == '') {
            return json(['status' => 100, 'msg' => '支付失败']);
        }
        $wx = new Wechat();
        $obj = [
            'attach'       => "QRcodePay",
            'body'         => "扫码支付",
            'total_fee'    => $money * 100,
            'out_trade_no' => time(),
            'product_id'   => "",
            'trade_type'   => "JSAPI",
            'openid'       => $openid
        ];
        $noty_url = http_type() . '/api/Wechat/huidiao';
        if($type == 2) $noty_url = http_type() . '/api/Wechat/huidiao1';
        $res = $wx->WeChatPayReady($obj, $noty_url);
        return json(['status' => 200, 'msg' => $res]);
    }
    /**
     * 续存支付成功后的回调
     */
    public function payBack(){
        $order_number = '123456';
        $order = Db::table('up_order')
            ->where('order_number', $order_number)
            ->field('order_id, order_jc_total_days, order_jc_sy_days, order_jc_datetime, 
            order_jc_date, order_is_pay, order_jc_now_price')
            ->find();
        $oi = Db::table('up_order_info')
            ->where('oi_order_id', $order['order_id'])
            ->where('oi_type', 2)
            ->field('oi_days, oi_price, oi_zhejiu_price, oi_id, oi_pay')
            ->order('oi_time desc')
            ->find();
        
        $dq_time = date('Y-m-d H:i:s', strtotime("+{$oi['oi_days']}days", strtotime($order['order_jc_datetime'])));
        $dq_date = date('Y-m-d', strtotime("+{$oi['oi_days']}days", strtotime($order['order_jc_date'])));
        
        if($order['order_is_pay'] == 1){
            Db::table('up_order')->where('order_id', $order['order_id'])
                ->update([
                    'order_is_pay' => 2,
                    'order_pay_time' => $this->create_time,
                    'order_jc_now_price' => $order['order_jc_now_price'] - $oi['oi_zhejiu_price'],
                    'order_jc_total_days' => $order['order_jc_total_days'] + $oi['oi_days'],
                    'order_jc_price' => $oi['oi_price'],
                    'order_jc_days' => $oi['oi_days'],
                    'order_jc_sy_days' => $order['order_jc_sy_days'] + $oi['oi_days'],
                    'order_jc_datetime' => $dq_time,
                    'order_jc_date' => $dq_date
                ]);
            
            Db::table('up_order_info')->where('oi_id', $oi['oi_id'])
                ->update([
                    'oi_pay' => 2
                ]);
        }
    }
    
    /**
     * 去还款支付成功后的回调
     */
    public function payBackToOverOrder(){
        $order_number = '123456';
        $order = Db::table('up_order')
            ->where('order_number', $order_number)
            ->field('order_id, order_is_pay')
            ->find();
    
        $oi = Db::table('up_order_info')
            ->where('oi_order_id', $order['order_id'])
            ->where('oi_type', 2)
            ->field('oi_days, oi_price, oi_zhejiu_price, oi_id, oi_pay')
            ->order('oi_time desc')
            ->find();
    
        if($order['order_is_pay'] == 1){
            Db::table('up_order')->where('order_id', $order['order_id'])
                ->update([
                    'order_is_pay' => 2,
                    'order_status' => 7,
                    'order_pay_time' => $this->create_time
                ]);
    
            Db::table('up_order_info')->where('oi_id', $oi['oi_id'])
                ->update([
                    'oi_pay' => 2
                ]);
        }
    }
}